package cc.vv.baselibrary.util.router;

import android.text.TextUtils;

import java.lang.reflect.Field;
import cc.vv.lkrouter.router.RouterActivity;
import cc.vv.lkrouter.router.RouterV4Fragment;

/**
 * 项目内部模块定点路由配置
 *
 * @author: NPF
 * @date: 2018/3/13.
 */
public class RouterConfig {

    private static RouterConfig mInstance;

    private RouterConfig() {
    }

    public static RouterConfig getInstance() {
        if (null == mInstance) {
            synchronized (RouterConfig.class) {
                if (null == mInstance) {
                    mInstance = new RouterConfig();
                }
            }
        }
        return mInstance;
    }

    /**
     * 跨模块路由配置
     * Activity、Fragment
     */
    public void initRouter() {
        initAllRouteIntentResource();
    }

    /** 初始化所有的路由资源*/
    private void initAllRouteIntentResource(){
        initTypeRouteIntentResource(0);
        initTypeRouteIntentResource(1);
        initTypeRouteIntentResource(2);
    }

    /** 初始化对应类型所有的路由资源
     * @param type 0:Activity;1:Fragment;
     * */
    private void initTypeRouteIntentResource(int type){
        Field[] fields = null;
        if(type == 0){
            fields = RouterActivityIntentResourceKey.class.getFields();
        }else if(type == 1){
            fields = RouterFragmentIntentResourceKey.class.getFields();
        }else if(type == 2){
            fields = RouterHttpClassKey.class.getFields();
        }
        if(fields!=null){
            for (int i = 0; i < fields.length; i++) {
                String name = fields[i].getName();
                String value = "";
                try {
                    value = fields[i].get(name)+"";
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if(!TextUtils.isEmpty(value)){
                    Class correspondingClass = getCorrespondingClass(value);
//                    LogOperate.e(correspondingClass+"");
                    if(null != correspondingClass){
                        if(type == 0){
                            RouterActivity.getinstance().routerV(value,correspondingClass);
                        }else if(type == 1){
                            RouterV4Fragment.getInstance().routerV(value,correspondingClass);
                        }else if(type == 2){
                            RouterClassUtil.getInstance().routerV(value,correspondingClass);
                        }
                    }
                }
            }
        }
    }

    /** 根据类名获取对应的Class文件*/
    private Class getCorrespondingClass(String classStr){
        try {
            if(!TextUtils.isEmpty(classStr)){
                return Class.forName(classStr);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
